package com.xinchuang.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinchuang.comment.KeyWord;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.io.File;

/**
 * 解决跨域问题
 * @author xinchuang
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Resource
    private KeyWord keyWord;

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePathPatterns = new ArrayList<String>();
        excludePathPatterns.add("/login/**");
        excludePathPatterns.add("/file/**");
        excludePathPatterns.add("/swagger**/**");
        excludePathPatterns.add("/webjars/**");
        excludePathPatterns.add("/v3/**");
        registry.addInterceptor(requestInterceptor()).addPathPatterns("/**").excludePathPatterns(excludePathPatterns);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        File file = new File(keyWord.getFileUrl() + "/file");
        if (!file.exists()) {
            file.mkdirs();
        }
        //文件映射
        registry.addResourceHandler("/file/**").addResourceLocations("file:" + keyWord.getFileUrl() + "/file/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
//                        .allowedOrigins("*")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                .maxAge(3600);
    }

    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        return objectMapper;
    }
}
